package com.itheima.rocketmq.rocketmqdemo.order;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 发送顺序消息
 * @description:
 * @author: ycc
 * @time: 2021/3/24
 */
public class Product {
    public static void main(String[] args) throws Exception {
//        1.创建消息生产者producer，并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group1");
//        2.指定Nameserver地址
        producer.setNamesrvAddr("127.0.0.1:9876;127.0.0.1:9877");
//        3.启动producer
        producer.start();
        List<OrderStep> orderSteps = OrderStep.buildOrder();

        for (int i=0;i<orderSteps.size();i++){
            String body = orderSteps.get(i)+"";
//        4.创建消息对象，指定主题Topic、Tag和消息体
            Message msg = new Message("OrderTopic","Order"+(""+i),body.getBytes());
//        5.发送消息
//            SendResult result = producer.send(msg);
//            System.out.println("result：------"+result);
//            TimeUnit.SECONDS.sleep(1);
            /**
             * 第一个参数:消息对象
             * 第二个参数:消息队列的选择器
             * 第三个参数：选择队列的业务标识（订单id）
             */
            SendResult result = producer.send(msg, new MessageQueueSelector() {
                /**
                 * 消息队列的选择器
                 * @param mqs:队列集合
                 * @param msg:消息对象
                 * @param arg:业务标识参数
                 * @return
                 */
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
//                    mqs.forEach(messageQueue->{
//                        System.out.println("----------->"+messageQueue.getQueueId());
//                    });
                    long orderId = (long) arg;
                    long index = orderId % mqs.size();
                    System.out.println("mqs.size():【"+mqs.size()+"】orderId:【"+orderId+"】========"+index);
                    return mqs.get((int) index);
                }
            }, orderSteps.get(i).getOrderId(),1000);
        }
//        6.关闭生产者producer
        producer.shutdown();
    }
}


